package com.yy.bolg.controller.hik;

import com.alibaba.fastjson.JSON;
import com.yy.bolg.constant.ResultCode;
import com.yy.bolg.entity.CustomerBean;
import com.yy.bolg.entity.FeedbackBean;
import com.yy.bolg.entity.hik.ReceiveFaultNotificationsBean;
import com.yy.bolg.entity.hik.ReceiveWarningNotificationsBean;
import com.yy.bolg.service.CustomerService;
import com.yy.bolg.service.FeedbackService;
import com.yy.bolg.util.CodeGenerateUtil;
import com.yy.bolg.util.RespenseJsonTransformationUtil;
import com.yy.bolg.util.hikfirecloud.HikFireCloudDictionaries;
import com.yy.bolg.ws.WebSocket;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;

/**
 * 海康接收订阅消息通知控制器
 * @author enmaoFu
 * @date 2024-12-14
 * RequestMapping("/hik/receive/notifications) 是说明这个类的访问地址是 /hik/receive/notifications
 */
@Api(tags = {"海康接收订阅消息通知（海康物联网平台用）"})
@Controller
@RequestMapping(value = "/hik/receive/notifications")
public class ReceiveMessageNotificationsController {

    @Autowired
    private FeedbackService feedbackService;// 自动载入Service对象

    @Autowired
    private CustomerService customerService;// 自动载入Service对象

    @Autowired
    private WebSocket webSocket;// 自动载入Service对象

    /**
     * 接收报警推送
     * 服务器访问路径：http://localhost:8080/bolg/hik/receive/notifications/waring
     * 本地访问路径：http://localhost:8111/hik/receive/notifications/waring
     * 参数参考URL：https://open.hikfirecloud.com/artemis-portal/document/92#doc1
     */
    @ApiOperation(value = "接收报警推送", notes = "参数参考URL：https://open.hikfirecloud.com/artemis-portal/document/92#doc1")
    @RequestMapping(value = "/waring",method = RequestMethod.POST, produces="text/html;charset=UTF-8")
    @ResponseBody
    public String waring(@RequestBody String str){
        String result = RespenseJsonTransformationUtil.jsonStr(ResultCode.CODE_SUCCESS, "接收报警推送成功",new HashMap());
        try {
            webSocket.sendMessageAll(result);
            ReceiveWarningNotificationsBean bean = JSON.parseObject(str, ReceiveWarningNotificationsBean.class);
            for(ReceiveWarningNotificationsBean.FpsBean.MsgListBean msgBean: bean.getFps().getMsgList()){
                for(ReceiveWarningNotificationsBean.FpsBean.MsgListBean.BodyBean.DataBean dataBean: msgBean.getBody().getData()){
                    CustomerBean customerBean = new CustomerBean();
                    customerBean.setPsCustomerUnitid(dataBean.getUnitID());
                    CustomerBean returnBean = customerService.findOneByHikUnitId(customerBean);
                    FeedbackBean feedbackBean = new FeedbackBean();
                    feedbackBean.setPsFeedbackCode(CodeGenerateUtil.getFeedbackCode());
                    feedbackBean.setPsCustomerCode(returnBean.getPsCustomerCode());
                    feedbackBean.setPsFeedbackContent(
                            dataBean.getResourceName() +
                            HikFireCloudDictionaries.getResourceTypeStr(dataBean.getResourceType()) +
                            "发生" +
                            HikFireCloudDictionaries.getAlarmTypeStr(dataBean.getAlarmType()));
                    feedbackBean.setPsFeedbackVoiceFile("海康预警推送无音频文件");
                    feedbackBean.setPsFeedbackVideoFile("海康预警推送无视频文件");
                    if(null != dataBean.getAlarmURLs() && null != dataBean.getAlarmURLs().getAlarmURLs() && dataBean.getAlarmURLs().getAlarmURLs().size() != 0){
                        StringBuilder img = new StringBuilder();
                        for(ReceiveWarningNotificationsBean.FpsBean.MsgListBean.BodyBean.DataBean.AlarmURLsBeanX.AlarmURLsBean imgUrl: dataBean.getAlarmURLs().getAlarmURLs()){
                            img.append(",").append(imgUrl.getPicURL());
                        }
                        feedbackBean.setPsFeedbackImgFile(img.substring(1));
                        System.out.println(img.substring(1));
                    }else{
                        feedbackBean.setPsFeedbackImgFile("海康预警推送无图片");
                    }
                    feedbackBean.setPsFeedbackProvince(returnBean.getPsCustomerProvince());
                    feedbackBean.setPsFeedbackCity(returnBean.getPsCustomerCity());
                    feedbackBean.setPsFeedbackRegion(returnBean.getPsCustomerRegion());
                    feedbackBean.setPsFeedbackAddress(returnBean.getPsCustomerAddress());
                    feedbackBean.setPsFeedbackLongitude(returnBean.getPsCustomerLongitude());
                    feedbackBean.setPsFeedbackLatitude(returnBean.getPsCustomerLatitude());
                    feedbackBean.setPsFeedbackType(1);
                    feedbackBean.setPsFeedbackState(1);
                    feedbackBean.setPsFeedbackClassification(1);
                    feedbackBean.setPsFeedbackHikFirstDate(dataBean.getAlarmStartTime().substring(0,19).replace("T"," "));
                    feedbackBean.setPsFeedbackHikNewDate(dataBean.getAlarmTime().substring(0,19).replace("T"," "));
                    feedbackBean.setPsFeedbackHikAddress(dataBean.getAreaName());
                    if(HikFireCloudDictionaries.getDeviceTypeStr(dataBean.getDeviceType()).contains("未知")){
                        feedbackBean.setPsFeedbackHikDeviceType(HikFireCloudDictionaries.getDeviceTypeStr(dataBean.getDeviceType()));
                    }else{
                        feedbackBean.setPsFeedbackHikDeviceType(HikFireCloudDictionaries.getSensorTypeStr(dataBean.getDeviceType()));
                    }
                    feedbackBean.setPsFeedbackHikDeviceSerial(dataBean.getResourceSerial());
                    List<FeedbackBean> feedbackBeanList = feedbackService.findAllBySerialDate(feedbackBean);

                    if(feedbackBeanList.size() < 5){
                        feedbackBean.setPsFeedbackGlance(0);
                        feedbackBean.setPsFeedbackGlanceServer(0);

                        // TODO 当天同一序列号设备上报故障或预计不超过5条时，才发送短信
                    }else{
                        feedbackBean.setPsFeedbackGlance(1);
                        feedbackBean.setPsFeedbackGlanceServer(1);
                    }

                    System.out.println(feedbackBean.getPsFeedbackContent());
                    feedbackService.addHik(feedbackBean);


                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = RespenseJsonTransformationUtil.jsonStr(ResultCode.CODE_FAIL, e.getMessage(),new HashMap());
        }
        return result;
    }

    /**
     * 接收故障推送
     * 服务器访问路径：http://localhost:8080/bolg/hik/receive/notifications/fault
     * 本地访问路径：http://localhost:8111/hik/receive/notifications/fault
     * 参数参考URL：https://open.hikfirecloud.com/artemis-portal/document/92#doc2
     */
    @ApiOperation(value = "接收故障推送", notes = "参数参考URL：https://open.hikfirecloud.com/artemis-portal/document/92#doc2")
    @RequestMapping(value = "/fault",method = RequestMethod.POST, produces="text/html;charset=UTF-8")
    @ResponseBody
    public String fault(@RequestBody String str){
        String result = RespenseJsonTransformationUtil.jsonStr(ResultCode.CODE_SUCCESS, "接收故障推送成功",new HashMap());
        try {
            webSocket.sendMessageAll(result);
            ReceiveFaultNotificationsBean bean = JSON.parseObject(str, ReceiveFaultNotificationsBean.class);
            for(ReceiveFaultNotificationsBean.FpsBean.MsgListBean msgBean: bean.getFps().getMsgList()){
                for(ReceiveFaultNotificationsBean.FpsBean.MsgListBean.BodyBean.DataBean dataBean: msgBean.getBody().getData()){
                    CustomerBean customerBean = new CustomerBean();
                    customerBean.setPsCustomerUnitid(dataBean.getUnitID());
                    CustomerBean returnBean = customerService.findOneByHikUnitId(customerBean);
                    FeedbackBean feedbackBean = new FeedbackBean();
                    feedbackBean.setPsFeedbackCode(CodeGenerateUtil.getFeedbackCode());
                    feedbackBean.setPsCustomerCode(returnBean.getPsCustomerCode());
                    feedbackBean.setPsFeedbackContent(
                            dataBean.getResourceName() +
                                    HikFireCloudDictionaries.getResourceTypeStr(dataBean.getResourceType()) +
                                    "发生" +
                                    HikFireCloudDictionaries.getFaultTypeStr(dataBean.getFaultType()));
                    feedbackBean.setPsFeedbackVoiceFile("海康预警推送无音频文件");
                    feedbackBean.setPsFeedbackVideoFile("海康预警推送无视频文件");
                    feedbackBean.setPsFeedbackImgFile("海康故障推送无图片");
                    feedbackBean.setPsFeedbackProvince(returnBean.getPsCustomerProvince());
                    feedbackBean.setPsFeedbackCity(returnBean.getPsCustomerCity());
                    feedbackBean.setPsFeedbackRegion(returnBean.getPsCustomerRegion());
                    feedbackBean.setPsFeedbackAddress(returnBean.getPsCustomerAddress());
                    feedbackBean.setPsFeedbackLongitude(returnBean.getPsCustomerLongitude());
                    feedbackBean.setPsFeedbackLatitude(returnBean.getPsCustomerLatitude());
                    feedbackBean.setPsFeedbackType(2);
                    feedbackBean.setPsFeedbackState(1);
                    feedbackBean.setPsFeedbackClassification(1);
                    feedbackBean.setPsFeedbackHikNewDate(dataBean.getFaultTime().substring(0,19).replace("T"," "));
                    feedbackBean.setPsFeedbackHikAddress(dataBean.getAreaName());
                    if(HikFireCloudDictionaries.getDeviceTypeStr(dataBean.getDeviceType()).contains("未知")){
                        feedbackBean.setPsFeedbackHikDeviceType(HikFireCloudDictionaries.getDeviceTypeStr(dataBean.getDeviceType()));
                    }else{
                        feedbackBean.setPsFeedbackHikDeviceType(HikFireCloudDictionaries.getSensorTypeStr(dataBean.getDeviceType()));
                    }
                    feedbackBean.setPsFeedbackHikDeviceSerial(dataBean.getResourceSerial());

                    List<FeedbackBean> feedbackBeanList = feedbackService.findAllBySerialDate(feedbackBean);
                    if(feedbackBeanList.size() < 5){
                        feedbackBean.setPsFeedbackGlance(0);
                        feedbackBean.setPsFeedbackGlanceServer(0);

                        // TODO 当天同一序列号设备上报故障或预计不超过5条时，才发送短信
                    }else{
                        feedbackBean.setPsFeedbackGlance(1);
                        feedbackBean.setPsFeedbackGlanceServer(1);
                    }

                    System.out.println(feedbackBean.getPsFeedbackContent());
                    feedbackService.addHik(feedbackBean);


                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = RespenseJsonTransformationUtil.jsonStr(ResultCode.CODE_FAIL, e.getMessage(),new HashMap());
        }
        return result;
    }

}
